//页面快速生成脚本
const path = require('path')
const fs = require('fs')
const template = require('art-template')
template.defaults.extname = '.html'
template.defaults.imports.toJson = function json(data) {
  let str = ''
  if (data === null) {
    return 'null'
  } else if (data === undefined) {
    return 'undefined'
  } else if (data.constructor === String) {
    return `'${data}'`
  } else if (data.constructor === Number) {
    return data
  } else if (data.constructor === Boolean) {
    return data
  } else if (data.constructor === Function) {
    return data.toString()
  } else if (data.constructor === RegExp) {
    return data.toString()
  } else if (data.constructor === Array) {
    let arrstr = '['
    data.forEach((item, index) => {
      data.length - 1 === index ? (arrstr += `${json(item)}]`) : (arrstr += `${json(item)},`)
    })
    return arrstr
  } else if (data.constructor === Object) {
    let objstr = '{'
    for (let key in data) {
      objstr += `'${key}':${json(data[key])},`
    }
    return objstr + '}'
  }
  return str
}
// 标准/默认路径

const srcUrl = path.resolve(__dirname, '../src')
const apiUrl = path.resolve(__dirname, '../src/api')
const viewsUrl = path.resolve(__dirname, '../src/views')
const routerUrl = path.resolve(__dirname, '../src/router')

// 默认数据来源
const filePath = path.resolve(__dirname, './data.json')
let fileConfig = []
function makeUrl(url, baseUrl = viewsUrl) {
  return path.join(baseUrl, url)
}
// 获取文件配置
function getFileConfig(filePath) {
  return new Promise(function (resolve, reject) {
    fs.readFile(filePath, 'utf8', function (error, data) {
      if (error) {
        reject(error)
      } else {
        resolve(data)
      }
    })
  })
}
// 检查参数
function chenkConfig(fileConfig) {
  if (fileConfig.length < 1) {
    console.log('配置文件内没有需要生成的模板数据')
    process.exit(0)
  } else {
    fileConfig.forEach(item => {
      createFiles(item)
    })
  }
}

// 创建外层目录
function wrap(config, baseUrl) {
  if (config.parentPath) {
    const parentPath = config.parentPath.split('/')
    parentPath.forEach(item => {
      try {
        fs.mkdirSync(makeUrl(`./${item}`, baseUrl))
        process.chdir(makeUrl(`./${item}`, baseUrl)) // cd views
        baseUrl = baseUrl + `/${item}`
      } catch (e) {
        if (e.message.indexOf('file already exists')) {
          baseUrl = baseUrl + `/${item}`
        } else {
          new Error(e)
        }
      }
    })
  }
  return baseUrl
}

// 生成页面
function createFiles(config) {
  // console.log(config)
  // 检查父级目录是否为 views ，默认为 views
  let baseUrl = viewsUrl
  baseUrl = wrap(config, baseUrl)
  // 创建菜单目录
  fs.mkdirSync(makeUrl(config.fileName, baseUrl))
  // 生成vue文件
  const VueTep = template(makeUrl(`template/vue-template.html`, __dirname), config)
  process.chdir(makeUrl(config.fileName, baseUrl)) // cd views
  fs.writeFileSync(`index.vue`, VueTep.replace(/&#34;/g, "'")) // vue
  // 暴露路由
  fs.writeFileSync(`route.js`, template(makeUrl(`template/route.html`, __dirname), config).replace(/&#34;/g, "'")) // route.js
  // 写入功能
  fs.mkdirSync(`${makeUrl(config.fileName, baseUrl)}/part`)
  process.chdir(`${makeUrl(config.fileName, baseUrl)}/part`)
  fs.writeFileSync(`detaile.vue`, template(makeUrl(`template/detaile.html`, __dirname), config).replace(/&#34;/g, "'")) // detaile.vue

  // 添加api 功能
  process.chdir(apiUrl) // cd views
  let apiBaseUrl = wrap(config, apiUrl)
  fs.mkdirSync(makeUrl(config.fileName, apiBaseUrl))
  process.chdir(makeUrl(config.fileName, apiBaseUrl)) // cd views
  fs.writeFileSync(`${config.fileName}.js`, template(makeUrl(`template/api.html`, __dirname), config)) // api.js

  // 添加路由
  process.chdir(routerUrl)
  getFileConfig(makeUrl('./routes.js', routerUrl))
    .then(res => {
      let oldContent = res
      let newContent = oldContent
        .replace(
          /\/\/@import/,
          `import ${config.fileName} from '../views/${config.parentPath ? config.parentPath + '/' : ''}${config.fileName}/route.js'\n//@import`,
        )
        .replace(/\/\/@export/, `//@export\n  ${config.fileName},`)
      // console.log(newContent)
      fs.writeFileSync('./routes.js', newContent)
    })
    .catch(res => {
      new Error(res)
    })
}

getFileConfig(filePath)
  .then(data => {
    fileConfig = JSON.parse(data)
    chenkConfig(fileConfig)
  })
  .catch(e => {
    console.log(e)
  })
